package goodbaby.dklt.customerview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;

import goodbaby.dklt.R;


public class ColorArcProgressBar extends View {

    private int mWidth;
    private int mHeight;
    private float centerX;  //圆心X坐标
    private float centerY;  //圆心Y坐标

    private Paint allArcPaint;
    private Paint progressPaint;
    private Paint curSpeedPaint;

    private RectF bgRect;

    private ValueAnimator progressAnimator;
    private PaintFlagsDrawFilter mDrawFilter;
    private SweepGradient sweepGradient;
    private Matrix rotateMatrix;

    private float backStartAngle = 0; //背景圆环开始角度
    private float backSweepAngle = 360; //背景圆环扫过的角度

    private float startAngle; //圆环的开始角度

    private float currentAngle = 0;

    private int[] colors = new int[]{Color.GREEN, Color.YELLOW, Color.RED, Color.RED};

    private float bgArcWidth = dipToPx(2);
    private float progressWidth = dipToPx(10);
    private float curSpeedSize = dipToPx(13);
    private int aniSpeed = 1000;


    private String hintColor = "#676767";

    private int bgArcColor = Color.BLUE;

    private OnSweepListener mListener;

    public ColorArcProgressBar(Context context) {
        super(context, null);
    }

    public ColorArcProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        initCofig(context, attrs);
    }

    public ColorArcProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCofig(context, attrs);
    }

    /**
     * 初始化布局配置
     *
     * @param context
     * @param attrs
     */
    private void initCofig(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorArcProgressBar);
        int color1 = a.getColor(R.styleable.ColorArcProgressBar_front_color1, Color.GREEN);
        int color2 = a.getColor(R.styleable.ColorArcProgressBar_front_color2, color1);
        int color3 = a.getColor(R.styleable.ColorArcProgressBar_front_color3, color1);
        colors = new int[]{color1, color2, color3, color3};

        bgArcColor = a.getColor(R.styleable.ColorArcProgressBar_back_color, color1);

        bgArcWidth = a.getDimension(R.styleable.ColorArcProgressBar_back_width, dipToPx(2));
        progressWidth = a.getDimension(R.styleable.ColorArcProgressBar_front_width, dipToPx(10));

        backStartAngle = a.getInteger(R.styleable.ColorArcProgressBar_back_start_angle, 0);
        backSweepAngle = a.getInteger(R.styleable.ColorArcProgressBar_back_sweep_angle, 360);


        a.recycle();

        //整个弧形
        allArcPaint = new Paint();
        allArcPaint.setAntiAlias(true);
        allArcPaint.setStyle(Paint.Style.STROKE);
        allArcPaint.setStrokeWidth(bgArcWidth);
        allArcPaint.setColor(bgArcColor);
        allArcPaint.setStrokeCap(Paint.Cap.ROUND);

        //当前进度的弧形
        progressPaint = new Paint();
        progressPaint.setAntiAlias(true);
        progressPaint.setStyle(Paint.Style.STROKE);
        progressPaint.setStrokeCap(Paint.Cap.ROUND);
        progressPaint.setStrokeWidth(progressWidth);
        progressPaint.setColor(Color.GREEN);


        //显示标题文字
        curSpeedPaint = new Paint();
        curSpeedPaint.setTextSize(curSpeedSize);
        curSpeedPaint.setColor(Color.parseColor(hintColor));
        curSpeedPaint.setTextAlign(Paint.Align.CENTER);

        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

        rotateMatrix = new Matrix();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        Log.i("onMeasure", mWidth + "," + mHeight);


        //弧形的矩阵区域
        bgRect = new RectF();
        float dValue = progressWidth > bgArcWidth ? progressWidth / 2 : bgArcWidth / 2;
        bgRect.top = dValue;
        bgRect.left = dValue;
        bgRect.right = mWidth - dValue;
        bgRect.bottom = mHeight - dValue;

        //圆心
        centerX = mWidth / 2;
        centerY = mHeight / 2;

    }

    @Override
    protected void onDraw(Canvas canvas) {

        //抗锯齿
        canvas.setDrawFilter(mDrawFilter);

        //整个弧
        canvas.drawArc(bgRect, backStartAngle, backSweepAngle, false, allArcPaint);

        //设置渐变色
        rotateMatrix.setRotate(startAngle - progressWidth / 2, centerX, centerY);
        if (sweepGradient == null) {
            sweepGradient = new SweepGradient(centerX, centerY, colors, null);
        }
        sweepGradient.setLocalMatrix(rotateMatrix);
        progressPaint.setShader(sweepGradient);

        //当前进度
        canvas.drawArc(bgRect, startAngle, currentAngle, false, progressPaint);

        /*if (isNeedContent) {
            canvas.drawText(String.format("%.0f", curValues), centerX, centerY + textSize / 3, vTextPaint);
        }
        if (isNeedUnit) {
            canvas.drawText(hintString, centerX, centerY + 2 * textSize / 3, hintPaint);
        }
        if (isNeedTitle) {
            canvas.drawText(titleString, centerX, centerY - 2 * textSize / 3, curSpeedPaint);
        }*/


    }

    public void sweepAnimation(final float startAngle, final float sweepAngle) {
        this.startAngle = startAngle;
        currentAngle = 0;
        progressAnimator = ValueAnimator.ofFloat(currentAngle, sweepAngle);
        progressAnimator.setInterpolator(new DecelerateInterpolator());
        progressAnimator.setDuration(aniSpeed);
        progressAnimator.setTarget(currentAngle);
        progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentAngle = (float) animation.getAnimatedValue();
                if (currentAngle != 0) {
                    invalidate();
                }

                if (mListener != null) {
                    mListener.onSweep(startAngle, currentAngle, sweepAngle);
                }
            }
        });
        progressAnimator.start();
    }

    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    private int dipToPx(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }

    /**
     * 得到屏幕宽度
     *
     * @return
     */
    private int getScreenWidth() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    public void setOnSweepListener(OnSweepListener listener) {
        mListener = listener;
    }

    public interface OnSweepListener {
        /**
         * @param startAngle
         * @param currAngle
         * @param endAngle
         */
        void onSweep(float startAngle, float currAngle, float endAngle);
    }

}
